const tinify = require("tinify");
const fs = require("fs");
const path = require("path");

// 设置 TinyPNG API Key
tinify.key = "kvTJK7H6VHt568hypc14cqVTRvzNK0pz";

// 压缩单张图片
async function compressImage(inputPath, outputPath) {
  try {
    await tinify.fromFile(inputPath).toFile(outputPath);
    console.log(`压缩成功: ${inputPath} -> ${outputPath}`);
  } catch (error) {
    console.error(`压缩失败: ${inputPath} - 错误: ${error.message}`);
  }
}

// 递归压缩文件夹
async function compressDirectoryRecursively(inputDir, outputDir) {
  // 确保输出目录存在
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  const files = fs.readdirSync(inputDir);

  for (const file of files) {
    const inputFilePath = path.join(inputDir, file);
    const outputFilePath = path.join(outputDir, file);
    const stat = fs.lstatSync(inputFilePath);

    if (stat.isDirectory()) {
      // 递归处理子文件夹
      await compressDirectoryRecursively(inputFilePath, outputFilePath);
    } else if (stat.isFile() && /\.(jpg|jpeg|png)$/i.test(file)) {
      // 压缩图片，保持原文件名
      await compressImage(inputFilePath, outputFilePath);
    }
  }
}

// 调用函数
const inputFolder = "./images"; // 输入文件夹
const outputFolder = "./images_compressed"; // 输出文件夹，保留原目录结构
compressDirectoryRecursively(inputFolder, outputFolder);
